var express = require('express');
var fs = require('fs');
var router = express.Router();

var APIDOC_DATA_BASE_PATH = "../api";

/*  home page. */
router.all('/', function (req, res) {
    var requestPath = req.baseUrl;
    if (isNull(requestPath)) {
        res.json({"code": 400, "msg": "请求路径不正确"});
        return;
    }
    var pathUrls = requestPath.split("/");
    if (pathUrls.length < 3) {
        res.json({"code": 400, "msg": "请求路径不正确"});
        return;
    }
    var projectName = pathUrls[1];
    var requestUrl = requestPath.substr(1 + projectName.length);
    var matchedDataArray = getMatchedDataArray(projectName, requestUrl);
    if (isNull(matchedDataArray) || matchedDataArray.length <= 0) {
        res.json({"code": 400, "msg": "请求路径不匹配"});
        return;
    }
    var matchedData = null;
    for(i in matchedDataArray){
        data = matchedDataArray[i];
        if (req.method != data.type) {
            continue;
        }
        matchedData = data;
        break;
    }
    if(isNull(matchedData)){
        res.json({"code": 400, "msg": "请求方式不正确"});
        return;
    }
    if (matchedData.hasOwnProperty("success") && matchedData.success.hasOwnProperty("examples")) {
            var exampleArray = []
            for (i in matchedData.success.examples) {
                var example = matchedData.success.examples[i];
                exampleArray.push(example)
            }
            var example = exampleArray[Math.floor(Math.random() * exampleArray.length)];
            try {
                var content = JSON.parse(example.content)
                res.json(content)
                return
            } catch (e) {
                res.json({"code": 400, "msg": "示例数据格式不正确，请检查", "data": example.content});
                return
            }
    }
    res.json({"code": 400, "msg": "找不到匹配的示例数据"});
});

function getMatchedDataArray(projectName, requestUrl) {
    var api_data_path = APIDOC_DATA_BASE_PATH + "/" + projectName + "/api_data.json";
    // api_data_path = APIDOC_DATA_BASE_PATH + "/api_data.json";
    var dataArray = JSON.parse(fs.readFileSync(api_data_path, "utf-8"));
    var matchedDataArray = []
    for (i in dataArray) {
        var data = dataArray[i]
        var url = data.url;
        var regexUrl = getRegexUrl(url);
        if (regexUrl.test(requestUrl)) {
            matchedDataArray.push(data);
        }
    }
    return matchedDataArray;
}

function getRegexUrl(url) {
    if (isNull(url)) {
        return null;
    }
    var dataArray = url.split("/");
    dataArray.forEach(function (data, i) {
        if (data.startWith(":") || data.startWith("{") ) {
            dataArray[i] = "(\\w+)";
        }

    });
    return new RegExp(dataArray.join("/")+ "$");
}

function isNull(data) {
    return (data == "" || data == undefined || data == null) ? true : false;
}

String.prototype.startWith = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
}
module.exports = router;
